import React, { Component } from 'react';
import { StyleSheet, View, DeviceEventEmitter } from 'react-native';
import Swiper from 'react-native-swiper';
import List from './list';
import Info from './info';
import Search from './search';

class SparePart extends Component {
  componentDidMount() {
    global.mainIndex = 1;
    DeviceEventEmitter.addListener('swiperIncidentPageEvent', this.swiperIncidentPage);
  }

  componentWillUnmount() {
    DeviceEventEmitter.removeAllListeners('swiperIncidentPageEvent');
  }

  swiperIncidentPage = (index) => {
    if (this._Swiper) {
      this._Swiper.scrollBy(index);
    }
  }

  _indexChange = (index) => {
    DeviceEventEmitter.emit('showTopBarEvent', 'hide');
    global.mainIndex = index;
    if (index == '0') {
      DeviceEventEmitter.emit('swipeToSearch', null);
    } else if (index == '2') {
      const list = this.refs.derverList.state.list;
      const index = this.refs.derverList.index;
      const item = list[index];
      // console.log('----', item);
      if (item) { // 有数据
        DeviceEventEmitter.emit('swipeToDetail', {
          code: item.materialCode1,
        });
      } else { // 无数据
        DeviceEventEmitter.emit('swipeToDetail', null);
      }
    }
  }

  _Swiper;

  render() {
    return (
      <View style={styles.container}>
        <Swiper
          ref={(ref) => {
            this._Swiper = ref;
          }}
          style={styles.wrapper}
          horizontal
          onIndexChanged={(index) => this._indexChange(index)}
          showsPagination={false}
          index={1}
          loop={false}
        >
          <View style={styles.slide}>
            <Search />
          </View>
          <View style={styles.slide}>
            <List ref="derverList" changePageIndex={this.props.changePageIndex} />
          </View>
          <View style={styles.slide}>
            <Info />
          </View>
        </Swiper>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  slide: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#fff',
  },
});

export default SparePart;
